package com.hm.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hm.base.auto.SystemEnvConfigProperties;
import com.hm.base.auto.su.BeanUtil;
import com.hm.base.def.UserSexEnum;
import com.hm.base.domain.Subscriber;
import com.hm.base.mapper.SubscriberMapper;
import com.hm.base.service.SubscriberService;
import com.hm.base.vo.SubscriberVo;
import com.hm.common.def.DataStatusDef;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.PageInfo;
import com.hm.common.su.bean.PageInfo.PageParam;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;
import com.hm.common.util.EncryptUtil.Md5;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午2:56:49 2017年6月2日
 * @version 1.0
 * @describe
 */
@Slf4j
@Service
public class SubscriberServiceImpl implements SubscriberService {

	@Autowired
	private SubscriberMapper subscriberMapper;

	@Autowired
	private SystemEnvConfigProperties systemEnvConfigProperties;

	@Override
	public void addSubscriber(SubscriberVo subscriberVo) {
		if (CommonUtil.isAnyEmpty(subscriberVo.getAccount(), subscriberVo.getUserName(), subscriberVo.getUserPwd(),
				subscriberVo.getEmail(), subscriberVo.getPhone())) {
			log.error("添加系统账户,必填参数缺失");
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		if (CommonUtil.isEmpty(subscriberMapper.checkUsername(subscriberVo.getUserName()))) {
			throw ServiceException.warn("用户名已存在");
		}

		if (CommonUtil.isEmpty(subscriberMapper.checkAccount(subscriberVo.getAccount()))) {
			throw ServiceException.warn("用户账户已存在");
		}

		if (CommonUtil.isEmpty(subscriberMapper.checkEmail(subscriberVo.getEmail()))) {
			throw ServiceException.warn("用户邮箱地址已存在");
		}

		if (CommonUtil.isEmpty(subscriberMapper.checkPhone(subscriberVo.getPhone()))) {
			throw ServiceException.warn("用户电话号码已存在");
		}

		Subscriber subscriber = new Subscriber();
		BeanUtil.copyProperties(subscriberVo, subscriber);

		Date now = new Date();
		subscriber.setCreateTime(now);
		subscriber.setLastLoginTime(now);
		subscriber.setStatus(DataStatusDef.ENABLE.name());
		subscriber.setUserPwd(Md5.getMD5Code(subscriber.getUserPwd()));
		subscriber.setId(null);

		subscriberMapper.insertSelective(subscriber);
	}

	@Override
	public PageInfo<SubscriberVo> query(PageParam pageParam, String account) {
		Page<Subscriber> page = PageHelper.startPage(pageParam.getPage(), pageParam.getSize(), true);

		Subscriber subscriberParam = new Subscriber();
		subscriberParam.setAccount(account);

		subscriberMapper.query(subscriberParam);
		List<SubscriberVo> vos = new ArrayList<SubscriberVo>();
		page.getResult().forEach(subscriber -> {
			SubscriberVo subscriberVo = new SubscriberVo();
			BeanUtil.copyProperties(subscriber, subscriberVo);
			subscriberVo.setLastLoginTime(DateUtil.data2long(subscriber.getLastLoginTime()));
			subscriberVo.setCreateTime(DateUtil.data2long(subscriber.getCreateTime()));
			subscriberVo.setSex(UserSexEnum.trance(subscriber.getSex()));

			vos.add(subscriberVo);
		});

		return new PageInfo<SubscriberVo>(vos, page.getPages(), page.getTotal());
	}

	@Override
	public SubscriberVo getSubscriber(Long subscriberId) {
		if (CommonUtil.isEmpty(subscriberId)) {
			log.error("获取登陆用户信息错误,id={}", subscriberId);
			throw ServiceException.warning(ErrorCode.DATA_NOT_NULL, "登录用户ID");
		}
		Subscriber subscriber = subscriberMapper.selectByPrimaryKey(subscriberId);
		if (CommonUtil.isEmpty(subscriber)) {
			log.error("{},登陆用户信息找不到", subscriberId);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}
		SubscriberVo subscriberVo = new SubscriberVo();
		BeanUtil.copyProperties(subscriber, subscriberVo);
		subscriberVo.setLastLoginTime(DateUtil.data2long(subscriber.getLastLoginTime()));
		subscriberVo.setCreateTime(DateUtil.data2long(subscriber.getCreateTime()));
		subscriberVo.setSex(UserSexEnum.trance(subscriber.getSex()));
		subscriberVo.setUserPwd(null);

		return subscriberVo;
	}

	@Override
	public void deleteSubscriber(List<Long> subscriberIds) {
		if (CommonUtil.isEmpty(subscriberIds)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		subscriberIds.parallelStream().forEach(subscriberId ->{
			
			Subscriber subscriber = subscriberMapper.selectByPrimaryKey(subscriberId);
			if (CommonUtil.isEmpty(subscriber)) {
				log.error("{},用户信息找不到", subscriberId);
				return;
			}

			if (systemEnvConfigProperties.isProtectInitUser() && 1 == subscriberId) {
				log.error("{},用户系统配置了保护,无权删除数据", subscriberId);
				return;
			}

			subscriber.setStatus(DataStatusDef.DISABLE.name());
			subscriberMapper.updateByPrimaryKey(subscriber);
		});
	}

	@Override
	public void updateSubscriber(Long subscriberId, SubscriberVo subscriberVo) {
		if (CommonUtil.isAnyEmpty(subscriberId, subscriberVo.getSex(), subscriberVo.getEmail(), subscriberVo.getPhone(),
				subscriberVo.getUserName())) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		Subscriber subscriber = subscriberMapper.selectByPrimaryKey(subscriberId);
		if (CommonUtil.isEmpty(subscriber)) {
			log.error("{},用户信息找不到", subscriberId);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		subscriber.setSex(subscriberVo.getSex().name());
		subscriber.setEmail(subscriberVo.getEmail());
		subscriber.setPhone(subscriberVo.getPhone());
		subscriber.setUserName(subscriberVo.getUserName());

		subscriberMapper.updateByPrimaryKey(subscriber);

	}

	@Override
	public void updateSubscriberPwd(Long subscriberId, String oldPwd, String newPwd) {
		if (CommonUtil.isAnyEmpty(subscriberId, newPwd)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}

		Subscriber subscriber = subscriberMapper.selectByPrimaryKey(subscriberId);
		if (CommonUtil.isEmpty(subscriber)) {
			log.error("{},用户信息找不到", subscriberId);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		if (CommonUtil.isEmpty(oldPwd)) {
			subscriber.setUserPwd(Md5.getMD5Code(newPwd));
			subscriberMapper.updateByPrimaryKey(subscriber);
			return;
		}

		if (!Md5.getMD5Code(oldPwd).equals(subscriber.getUserPwd())) {
			throw ServiceException.warn("旧密码错误,修改登录密码失败");
		}
		subscriber.setUserPwd(Md5.getMD5Code(newPwd));
		subscriberMapper.updateByPrimaryKey(subscriber);
	}

}
